import { Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core';
import { FetchService } from '../../../../core/net/fetch.service';
import * as moment from 'moment';
import { NzInputDirective, NzMessageService, NzModalService } from 'ng-zorro-antd';
import * as _ from 'lodash';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-mng-lake',
  templateUrl: './mng-lake.component.html',
  styleUrls: ['../mng-water-report.component.scss']
})
export class MngLakeComponent implements OnInit {

  listData = [];

  contentTitle: string;
  today: Date = new Date();
  datePicker: Date = new Date();
  range: Date[];
  quickTimeSelect = null;
  tableData = [];
  basicOpt: any = {
    title: {
      left: 'center',
      textStyle: {
        color: '#777',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['当日补水量', '累计补水量'],
      bottom: 0
    },
    color: ['#0092f1', '#ffbf44', '#1ada6f', '#12d0d2', '#ffdc00', '#f9383b'],
    // grid: {
    //     top: '10%',
    //     left: '3%',
    //     right: '4%',
    //     bottom: '8%',
    //     containLabel: true
    // },
    xAxis: [
      {
        type: 'category',
        data: [],
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '当日补水量（万m³）'
      },
      {
        type: 'value',
        name: '累计补水量（万m³）'
      }
    ],
    series: []
  };
  lakeOptChange: any = {};
  lakeEchartsIntance: any;
  historyData = [];
  frId: string;
  resDataCache: any;
  modalTitle: string = '湖泊湿地补水历史数据';
  modalShow: boolean = false;
  nzBodyStyle: any = {
    padding: '16px 20px 0'
  };
  modalFirstHead = {};
  objectKeys = Object.keys;
  editId: string | number;
  editCache: { [key: string]: { edit: boolean; data: any } } = {};

  @ViewChild(NzInputDirective, { read: ElementRef }) inputElement: ElementRef;

  // @HostListener('window:click', ['$event'])
  // handleClick(e: MouseEvent): void {
  //   console.log(e);
  //   if (this.inputElement && e.target['tagName'] !== 'INPUT') {
  //     Object.keys(this.editCache).forEach(key => {
  //       this.editCache[key].edit = false;
  //     });
  //   }
  // }

  constructor(private fetchService: FetchService,
              private http: HttpClient,
              private message: NzMessageService,
              private modal: NzModalService) {
  }

  ngOnInit() {
    this.fetchService.post<any>('muw/wrsMuwFr/list', { type: '3' }).subscribe(res => {
      this.frId = res[0].id;
      this.getDetailData();
    });
  }

  updateEditCache(): void {
    this.tableData.forEach(item => {
      this.calcSubTotal(item.prId);
      this.calcTotal();
      this.editCache[item.trLwId] = {
        edit: false,
        data: { ...item }
      };
    });
  }

  startEdit(trLwId: string | number, event: MouseEvent): void {
    event.preventDefault();
    event.stopPropagation();
    this.editId = trLwId;
    this.editCache[trLwId].edit = this.editCache[trLwId].data.rrName.indexOf('小计') < 0 && this.editCache[trLwId].data.rrName.indexOf('总计') < 0;
  }

  lakeChartInit(ec) {
    this.lakeEchartsIntance = ec;
  }

  resizeChart() {
    if (this.lakeEchartsIntance) {
      this.lakeEchartsIntance.resize();
    }
  }

  getDetailData(): void {
    const params = {
      frId: this.frId
    };
    this.fetchService.post<any>('muw/wrsMuwLwData/list', params).subscribe(res => {
      this.resDataCache = _.cloneDeep(res);
      this.tableData = _.sortBy(res.wrsMuwLwDatas, o => {
        o.val = o.hisVal;
        return o.prId;
      });
      this.updateEditCache();
      if (this.tableData.length) {
        this.getChartData(this.tableData[0]);
      }
    });
  }

  getChartData(row): void {
    this.fetchService.post<any>('muw/wrsMuwLwData/hisTrlwList', {
      stDate: moment().subtract(1, 'months').startOf('month').format('YYYY-MM-DD'),
      edDate: moment().format('YYYY-MM-DD'),
      // edDate: '2020-06-05',
      trLwId: row.trLwId
      // trLwId: '82'
    }).subscribe(res => {
      if (Array.isArray(res)) {
        setTimeout(() => {
          this.resizeChart();
        });
        this.lakeOptChange = {
          title: {
            text: `${row.rrName}补水量`
          },
          xAxis: {
            data: res.map(item => {
              return item.time;
            })
          },
          series: [
            {
              name: '当日补水量',
              type: 'bar',
              barWidth: '40%',
              data: res.map(item => {
                return item.val;
              })
            },
            {
              name: '累计补水量',
              type: 'line',
              smooth: true,
              yAxisIndex: 1,
              data: res.map(item => {
                return item.total;
              })
            }
          ]
        };
      }
    });
  }

  submit(): void {
    this.modal.confirm({
      nzTitle: '确认提交并上报？',
      nzContent: '',
      nzOnOk: () => {
        const table = _.cloneDeep(this.tableData);
        const data = _.assign(this.resDataCache, { statu: 2, wrsMuwLwDatas: table });
        this.fetchService.post<any>('muw/wrsMuwLwData/add', data).subscribe(res => {
          this.message.success('提交成功');
          this.getDetailData();
        });
      }
    });
  }

  save(): void {
    const table = _.cloneDeep(this.tableData);
    const data = _.assign(this.resDataCache, { statu: 1, wrsMuwLwDatas: table });
    this.fetchService.post<any>('muw/wrsMuwLwData/add', data).subscribe(res => {
      this.message.success('暂存成功');
      this.getDetailData();
    });
  }

  openDetailModal(): void {
    this.modalShow = true;
    this.quickTimeSelect = '7';
    this.quickSelect();
  }

  export(): void {
    const param = {
      frId: this.frId ? this.frId : ''
    };
    this.fetchService.export('muw/wrsMuwLwData/export', param).subscribe((res: any) => {
      const blob = new Blob([res], { type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8' });
      const elink = document.createElement('a');

      elink.download = `湖泊湿地补水量.xlsx`;
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    });
  }

  print(): void {
  }

  onCancel() {
    this.modalShow = false;
  }

  onRangeChange(result: Date[] | number[]): void {
    const start = result[0] ? moment(result[0]).valueOf() : moment().valueOf();
    const end = result[1] ? moment(result[1]).valueOf() : moment().valueOf();
    const params = {
      frId: this.frId,
      startDate: start,
      endDate: end
    };
    this.fetchService.post<any>('muw/wrsMuwLwData/historyDataList', params).subscribe(res => {
      res.forEach(item => {
        item.date = moment(item.time).format('YYYY-MM-DD');
      });
      this.historyData = _.reverse(res);
      this.historyData.forEach(item => {
        item.datas = _.reverse(item.wrsMuwLwDatas);
      });
      this.modalFirstHead = _.groupBy(this.historyData[0].datas, o => {
        return o.prName;
      });
    });
  }

  quickSelect(): void {
    const start = moment().subtract(parseInt(this.quickTimeSelect, 10), 'days').valueOf();
    const end = moment().valueOf();
    this.onRangeChange([start, end]);
  }

  calcRowspan(index, prId): number {
    const firstIndex = _.findIndex(this.tableData, o => {
      return o.prId === prId;
    });
    const lastIndex = _.findLastIndex(this.tableData, o => {
      return o.prId === prId;
    });
    return lastIndex - firstIndex + 1;
  }

  calcColspan(index, prId): number {
    const selectedItem = _.find(this.tableData, o => {
      return o.prId === prId;
    });
    return selectedItem.prName === selectedItem.rrName ? 2 : 1;
  }

  isTdShow(index, prId): boolean {
    const firstIndex = _.findIndex(this.tableData, o => {
      return o.prId === prId;
    });
    const lastIndex = _.findLastIndex(this.tableData, o => {
      return o.prId === prId;
    });
    return index <= firstIndex || index > lastIndex;
  }

  isColTdShow(index, prId): boolean {
    const selectedItem = _.find(this.tableData, o => {
      return o.prId === prId;
    });
    return selectedItem.prName !== selectedItem.rrName;
  }

  isHeadRowSpan(key): boolean {
    return this.modalFirstHead[key].length === 1 && this.modalFirstHead[key][0].prName === this.modalFirstHead[key][0].rrName;
  }

  stopEdit(prId): void {
    this.editId = null;
    Object.keys(this.editCache).forEach(key => {
      this.editCache[key].edit = false;
    });
    this.calcSubTotal(prId);
    this.calcTotal();
  }

  /**
   * 分组小计
   * @param prId
   */
  calcSubTotal(prId): void {
    const group = _.groupBy(this.tableData, 'prId')[prId];
    _.remove(group, item => {
      return item.rrName.indexOf('小计') > -1 || item.rrName.indexOf('总计') > -1;
    });

    this.tableData.forEach(item => {
      if (item.rrName.indexOf('小计') > -1 && item.prId === prId) {
        item['val'] = _.sum(group.map(o => {
          return Number(o.val);
        }));
      }
    });
  }

  /**
   * 总计
   */
  calcTotal(): void {
    const data = _.cloneDeep(this.tableData);
    _.remove(data, item => {
      return item.rrName.indexOf('小计') > -1 || item.rrName.indexOf('总计') > -1;
    });

    this.tableData.forEach(item => {
      if (item.rrName.indexOf('总计') > -1) {
        item['val'] = _.sum(data.map(o => {
          return Number(o.val);
        }));
      }
    });
  }
}
